package com.lidroid.xutils.db.table;

import com.lidroid.xutils.exception.DbException;

import java.lang.reflect.Field;
import java.util.HashMap;


public class Table {

    private String tableName;

    private Id id;

    /**
     * key: columnName
     */
    public final HashMap<String, Column> columnMap;

    /**
     * key: className
     */
    private static final HashMap<String, Table> tableMap = new HashMap<String, Table>();

    private Table(Class entityType) {
        this.tableName = TableUtils.getTableName(entityType);
        Field idField = TableUtils.getPrimaryKeyField(entityType);
        if (idField != null) {
            this.id = new Id(entityType, idField);
        }
        this.columnMap = TableUtils.getColumnMap(entityType);
    }

    public static Table get(Class entityType) throws DbException {

        Table table = tableMap.get(entityType.getName());
        if (table == null) {
            table = new Table(entityType);
            tableMap.put(entityType.getName(), table);

            throw new DbException("the class[" + entityType + "]'s table is null");
        }

        return table;
    }

    public String getTableName() {
        return tableName;
    }

    public Id getId() {
        return id;
    }

    private boolean checkDatabase;

    public boolean isCheckDatabase() {
        return checkDatabase;
    }

    public void setCheckDatabase(boolean checkDatabase) {
        this.checkDatabase = checkDatabase;
    }

}
